package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.RandomType;
import io.renren.common.utils.StringUtil;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dao.SysTenantDao;
import io.renren.modules.sys.dto.SysTenantDTO;
import io.renren.modules.sys.entity.SysTenantEntity;
import io.renren.modules.sys.enums.SuperAdminEnum;
import io.renren.modules.sys.service.SysTenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 租户表
 *
 * @author ch 842822530@qq.com
 * @since 1.0.0 2023-02-20
 */
@Service
public class SysTenantServiceImpl extends CrudServiceImpl<SysTenantDao, SysTenantEntity, SysTenantDTO> implements SysTenantService {

    @Override
    public QueryWrapper<SysTenantEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        Long tenantId = (Long)params.get("tenantId");

        QueryWrapper<SysTenantEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(ObjectUtils.isNotEmpty(tenantId),"tenant_id", tenantId);
        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysTenantDTO dto) {
        SysTenantEntity entity = ConvertUtils.sourceToTarget(dto, SysTenantEntity.class);
        //增加一块生成的租户id是否重复的判断
        entity.setTenantId(Long.parseLong(StringUtil.random(6, RandomType.INT)));

        //保存角色
        insert(entity);
    }


    /**
     * 根据租户id过滤列表
     * @param params
     * @return
     */
    @Override
    public List<SysTenantDTO> list(Map<String, Object> params) {
        //排除超管
        if (org.springframework.util.StringUtils.isEmpty(SecurityUser.getUser().getSuperAdmin()) || SecurityUser.getUser().getSuperAdmin() != SuperAdminEnum.YES.value()) {
            params.put("tenantId", SecurityUser.getTenantId());
        }
        List<SysTenantEntity> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, SysTenantDTO.class);

    }


}